package com.csc.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.csc.domain.Account;
import com.csc.domain.State;

/**
 * @author HoangHung
 */
@Repository
public class AccountDaoImpl implements AccountDao {

	@PersistenceContext
	private EntityManager em;

	static final Logger logger = Logger.getLogger(AccountDaoImpl.class);

	// HoangHung
	public Account findAccountInfoById(int accountId) {
		logger.info("find Account Info By Id Start");
		return em.find(Account.class, accountId);

	}

	// TrangNguyen
	public Account findAccountInfoByAccountInfoNumber(String accountNumber) {
		logger.info("Start Find Account By Number = " + accountNumber);

		// return em.find(Account.class, accountNumber);
		TypedQuery<Account> query = em
				.createQuery(
						"SELECT acc FROM Account acc WHERE acc.accountNumber =:accountNumber",
						Account.class).setParameter("accountNumber",
						accountNumber);

		List<Account> list = query.getResultList();
		if (list.size() == 0)
			return null;
		return list.get(0);
	}

	// HoangHung
	public List<Account> getListAccountByIdCardActive(String idCardNumber) {

		logger.info("getAccountListByIdCardNumber" + idCardNumber);
		TypedQuery<Account> query = em
				.createQuery(
						"SELECT acc FROM Account acc WHERE acc.idCustomer.idCardNumber =:idCardNumber and acc.idState.nameState = 'active'",
						Account.class);
		return query.setParameter("idCardNumber", idCardNumber).getResultList();

	}

	// HoangHung
	public List<Account> getAccountListByIdCardNumber(String idCardNumber) {

		logger.info("getAccountListByIdCardNumber" + idCardNumber);
		TypedQuery<Account> query = em
				.createQuery(
						"SELECT acc FROM Account acc WHERE acc.idCustomer.idCardNumber =:idCardNumber",
						Account.class);
		return query.setParameter("idCardNumber", idCardNumber).getResultList();
	}

	// HoangHung
	public List<Account> getAccountByAccountId(Integer accountId) {

		logger.info("get Account By AccountId" + accountId);
		TypedQuery<Account> query = em.createQuery(
				"SELECT acc FROM Account acc WHERE acc.accountId =:accountId",
				Account.class);
		return query.setParameter("accountId", accountId).getResultList();

	}

	// find State object
	public State findStateById(int stateId) {
		return em.find(State.class, stateId);
	}

	// update account
	public void updateAccount(Account account) {
		em.merge(account);		
	}

}
